/*
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-11-22 10:11:03
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-22 20:02:05
 */
import { TokenService } from '@package/service'
import { Message } from 'element-ui'
import { defineStore } from '@/common/config/defineStore'
import { apiGetRouter, apiGetUserPowers, apiPostLogin, apiGetLogout, apiGetUnReadCount } from '../api/index'
import { EnumApiCode } from '../../../../../../globalEnum.js'
import { pinias } from '../../../common/pinia/index.js'

// import { defineStore } from 'pinia'
// 第一个参数是应用程序中 store 的唯一 id
export default defineStore('login', {
  state: () => ({
    user: {},
    menus: [],
    perms: [],
    unreadCount: 0
  }),
  // 相当于 vue 中的 computed 计算属性 返回一个数值
  getters: {
    userInfo(state) {
      return state?.user ?? ''
    },
    /**
     * 权限菜单
     * @param state
     * @return {any}
     */
    permissionsMenu: (state) => state?.menus ?? '',
    /**
     * 权限菜单
     * @param state
     * @return {any}
     */
    permissionsActions: (state) => state?.perms ?? null,
    /**
     * 头像地址
     * @param state
     * @return {string}
     */
    avatar(state) {
      const url = state.user?.avatarUrl ?? ''
      return url.indexOf('##') !== -1 ? url.split('##')[0] : url
    },
    userName(state) {
      return state.user?.realName ?? ''
    },
    getMenuPerimis(state) {
      return (url) => {
        const list = JSON.stringify(state.menus)
        return list.indexOf(url) !== -1
      }
    }
  },
  actions: {
    LoginIn(userInfo) {
      return new Promise((resolve, reject) => {
        ;(async () => {
          try {
            const { data, code } = await apiPostLogin(userInfo)
            if (code === EnumApiCode.Success) {
              TokenService.setToken('Token', data.access_token)
              sessionStorage.clear()
              resolve()
            } else {
              reject()
            }
          } catch (error) {
            reject(error)
          }
        })()
      })
    },
    async getUserUnreadCount() {
      const { data } = await apiGetUnReadCount()
      this.unreadCount = data
    },
    getInfo() {
      return new Promise((resolve, reject) => {
        ;(async () => {
          try {
            const { data } = await apiGetUserPowers()
            this.user = data
            resolve(data)
          } catch (error) {
            reject(error)
          }
        })()
      })
    },
    // 退出系统
    LogOut() {
      return new Promise((resolve, reject) => {
        ;(async () => {
          try {
            const res = await apiGetLogout()
            // this.clearUserInfo()
            resolve(res)
          } catch (error) {
            reject(error)
          }
        })()
      })
    },
    // 清除用户信息
    clearUserInfo() {
      console.log(9999)
      return new Promise((resolve, reject) => {
        ;(async () => {
          this.user = {}
          this.menus = []
          this.perms = []
          this.unreadCount = 0
          TokenService.removeToken('Token')
          sessionStorage.clear()
          resolve()
        })()
      })
    },
    getUserMenus() {
      return new Promise((resolve, reject) => {
        ;(async () => {
          try {
            const { data } = await apiGetRouter()
            this.menus = data.menus
            this.perms = data.perms
            if (!this.menus?.length) {
              Message.error({
                message: '账号未开通权限,请联系管理员！'
              })
              reject()
            }
            resolve(data)
          } catch (error) {
            reject(error)
          }
        })()
      })
    },
    setAvatar(url) {
      this.user = { ...this.user, avatarUrl: url }
    }
  }
})
